package com.leetcode;

/**
 * 回文链表
 * 给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false
 *
 * @author winson
 * @create 2022-04-13 10:39
 */
public class PalindromeSolution {

    /**
     * 通过快慢指针，找到后半部分的数据，然后翻转后半部分，与前半部分进行比较
     * @param head
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        /**
         * 找到后半部分
         */
        ListNode firstHalfEnd = endOfFirstHalf(head);
        /**
         * 翻转
         */
        ListNode secondHalfStart = reverseList(firstHalfEnd.next);
        ListNode p1 = firstHalfEnd, p2 = secondHalfStart;
        boolean ans = true;
        while (true && p2 != null) {
            if (p1.val != p2.val) {
                ans = false;
                break;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        // 还原翻转的链表
        firstHalfEnd.next = reverseList(secondHalfStart);
        return ans;
    }

    private ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = temp;
        }
        return pre;
    }

    private ListNode endOfFirstHalf(ListNode head) {
        ListNode fast = head,slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }


}
